<template>
    <el-row class="home" :gutter="20">
        <!--功能区-->
        <el-card>
            <div class="tool">
                <el-button type="success" @click="toCompile" size="small">提交</el-button>
                <!--          <el-button type="success" size="small">执行</el-button>-->
            </div>
        </el-card>
        <!--代码编辑框-->
        <el-card class="tool">
            <div>
                <CodeMirror ref="codeMirror"></CodeMirror>
            </div>
        </el-card>
        <!--编译执行结果-->
        <el-card class="result">
            <!--显示结果与错误信息-->
            <div>
                <div class="okInfo" v-if="ok" style="width: 100%">
                    <!--显示执行结果-->

                    <pre>
执行结果：<span><el-button type="success" plain size="small">通过</el-button></span>
</pre>
                    <el-alert
                            type="success"
                            :closable="false"
                            style="width: 100%; height: auto">
                        <pre>{{result}}</pre>
                    </el-alert>
                </div>
                <div class="errorInfo" v-if="error" style="width: 100%">
<pre>
执行结果：<span><el-button type="danger" plain size="small">编译错误</el-button></span>
</pre>
                    <el-alert
                            type="error"
                            :closable="false"
                            style="width: auto; height: 100%">
                        <pre v-for="(it, index) in errorMsg" :key="index">{{it}}</pre>
                    </el-alert>
                </div>
            </div>
        </el-card>
    </el-row>
</template>

<script>
    import CodeMirror from '../../../components/CodeMirror'
    import axios from 'axios'

    export default {
        name: "CodeView",
        components: {
            CodeMirror
        },
        data() {
            return {
                result: '',  //执行结果
                errorMsg: [],//错误信息
                code: '',    //源代码

                //显示
                ok: false,
                error: false
            }
        },
        mounted() {
            this.connectWebsocket();
        },
        methods: {
            // 刷新 （如果出现编辑器样式问题，以及不能初始化赋值回显数据，可以进行刷新操作）
            refresh() {
                this.$refs.codeMirror.refresh()
            },
            // 获取编辑器的值
            getValue() {
                return this.$refs.codeMirror.code
            },
            // 回显赋值
            setValue() {
                this.$refs.codeMirror.setValue('回显的值:比如 function aa() {}')
            },
            //学生编译请求
            toCompile: function () {
                var that = this;
                //重置数据
                this.result = '';
                this.errorMsg = [];
                this.ok = false;
                this.error = false;

                //发送请求
                /*
                    接口: 学生编译
                    请求地址: http://localhost:8881/producer/common/guest/compile
                    请求方法: post
                    请求参数: source（源代码，字符串），args（方法参数，字符串数组）
                    响应内容: 编译结果
                */
                this.code = this.$refs.codeMirror.code;

                axios({
                    method: 'post',
                    url: 'http://localhost:8881/producer/common/guest/compile',
                    data: {
                        source: this.code
                    }
                }).then(function (response) {
                    var res = response.data;
                    if (res.code == 200) {
                        that.$message.success('提交成功！');
                    } else {
                        that.$message.error('提交失败！');
                    }
                }).catch(function (error) {
                    console.log(error);
                });
            },

            connectWebsocket() {
                let websocket;
                let that = this;

                if (typeof WebSocket === "undefined") {
                    console.log("您的浏览器不支持WebSocket");
                    return;
                } else {
                    let protocol = "ws";
                    let url = "";
                    if (window.location.protocol == "https:") {
                        protocol = "wss";
                    }
                    // `${protocol}://window.location.host/echo`;
                    //url = 'ws://localhost:8080/api/websocket/100';
                    url = `${protocol}://localhost:8882/consume/webSocket/000`;

                    // 打开一个websocket
                    websocket = new WebSocket(url);
                    // 建立连接
                    websocket.onopen = () => {
                        // 发送数据
                        websocket.send("Hi, I am client !");
                        console.log("websocket发送数据中...");
                    };
                    // 客户端接收服务端返回的数据
                    websocket.onmessage = evt => {
                        console.log("websocket返回的数据：", evt);
                        var res = evt.data;
                        res = JSON.parse(res);
                        if(res.code == 200){
                            that.result = res.data.res;
                            that.errorMsg = '编译成功';
                            that.ok = true;
                        }else{
                            that.errorMsg = res.data.detailMsg;
                            that.error = true;
                        }
                    };
                    // 发生错误时
                    websocket.onerror = evt => {
                        console.log("websocket错误：", evt);
                    };
                    // 关闭连接
                    websocket.onclose = evt => {
                        console.log("websocket关闭：", evt);
                    };
                }
            },
        },
        created: function () {
            localStorage.setItem("role", 3)
        }
    }
</script>

<style scoped>

</style>